package se.ytterman.jpcap.data.integer;

import java.lang.*;
import java.io.*;
import java.util.regex.*;

import se.ytterman.jpcap.data.BinaryData;

public class ByteBinaryData extends BinaryData {

    public ByteBinaryData(int byte_payload) {
	// Set byte value
	this.byte_payload = (byte_payload & 0xFF);
    }

    public ByteBinaryData(String byteValue) {
	// 
	String byte_pattern = "(0[X|x][0-9|A-F]{1,2})";
	Pattern p = Pattern.compile(byte_pattern);
	Matcher m = p.matcher(byteValue);

	// Perform basic check of format
	if(m.matches()) {
	    // Extract the hexadecimal digits
	    StringBuffer valueBuffer = new StringBuffer(byteValue);
	    String byteDigits = valueBuffer.substring(2);

	    // Assign byte value
	    this.byte_payload = Integer.parseInt(byteDigits, 16); 
	}
	else {
	    // XXX Throw exception
	}
    }


    public ByteBinaryData(InputStream frameInputStream) throws Exception {
	// Read data from stream
	this.read(frameInputStream);
    }

    public int getByte() {
	return this.byte_payload;
    }

    public void read(InputStream frameInputStream) throws Exception {
	// Create a data input stream
	DataInputStream frameDataStream = 
	    new DataInputStream(frameInputStream);
	
	// Read an unsigned byte from the stream
	this.byte_payload = frameDataStream.readUnsignedByte();
    }

    public void write(OutputStream frameOutputStream) throws Exception {
	// Create a data output stream
	DataOutputStream frameDataStream = 
	    new DataOutputStream(frameOutputStream);
	
	// Write an unsigned byte from the stream
	frameDataStream.writeByte(this.byte_payload);
    }    

    public String toString() {
	String byte_string = String.format("0X%02X", 
					   (this.byte_payload & 0xFF));

	return byte_string;
    }

    private int byte_payload;
}
